<!DOCTYPE html>
<html lang="zh_CN" xmlns:th="http://www.thymeleaf.org" xmlns:shiro="http://www.pollix.at/thymeleaf/shiro">
<head th:fragment="head">
	<base th:href="@{/}">
	<meta charset="utf-8">
	<title>新增</title>
	<meta name="renderer" content="webkit">
	<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
	<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
	<meta name="apple-mobile-web-app-status-bar-style" content="black">
	<meta name="apple-mobile-web-app-capable" content="yes">
	<meta name="format-detection" content="telephone=no">
	<link rel="stylesheet" href="static/layui/css/layui.css" media="all" />
	<link rel="stylesheet" type="text/css" href="static/jquery-easyui/themes/default/easyui.css">
	<link rel="stylesheet" type="text/css" href="static/jquery-easyui/themes/icon.css">
	<link rel="stylesheet" href="static/layui/css/layui.css" media="all" />
	<script type="text/javascript" src="static/layui/layui.js"></script>
	<script type="text/javascript" src="static/jquery-easyui/jquery.min.js"></script>
	<script type="text/javascript" src="static/jquery-easyui/jquery.easyui.min.js"></script>
	<script type="text/javascript" src="static/jquery-easyui/locale/easyui-lang-zh_CN.js"></script> 
	<style type="text/css">
		.layui-form-label {
		    white-space: nowrap;
		    width: 120px;
		    color: gray;
		}
	</style>
</head>
<body class="layui-fluid" th:fragment="body">
	<div class="layui-row">
		<div class="layui-col-md12">
			<form class="easyui-form" id="form" action="" autocomplete="off" style="padding-top: 1px;" data-options="novalidate:true">
				<div class="layui-card-header">销售订单表头信息</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">客户编码</label>
						<div class="layui-input-inline">
							<input name="customerCode" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">客户名称</label>
						<div class="layui-input-inline">
							<input name="customerName" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">客户订单号</label>
						<div class="layui-input-inline">
							<input name="customerOrder" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">内部订单号</label>
						<div class="layui-input-inline">
							<input name="orderNo" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">父级订单号</label>
						<div class="layui-input-inline">
							<input name="parentOrderNo" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">关联订单号</label>
						<div class="layui-input-inline">
							<input name="relatedOrder" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">承揽商</label>
						<div class="layui-input-inline">
							<input name="cls" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">产品类别</label>
						<div class="layui-input-inline">
							<input name="cplb" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">订单属性</label>
						<div class="layui-input-inline">
							<input name="ddsx" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
				</div>
				<div class="layui-form-item" style="margin-top: 20px;">
					<div class="layui-inline">
						<label class="layui-form-label">业务员</label>
						<div class="layui-input-inline">
							<input name="personName" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">创建时间</label>
						<div class="layui-input-inline">
							<input name="createTime" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
					<div class="layui-inline">
						<label class="layui-form-label">业务类型</label>
						<div class="layui-input-inline">
							<input name="ywlx" class="easyui-textbox" readonly="readonly">
						</div>
					</div>
				</div>
			</form>
			<div class="layui-card-header">销售订单表体信息</div>
			<div class="layui-row" style="margin-top: 5px;">
				<div class="layui-col-md12">
					<table id="table" class="layui-table" lay-filter="table"></table>
				</div>
			</div>
			<div class="layui-card-header">订单工序信息</div>
			<div class="layui-row" style="margin-top: 5px;">
				<div class="layui-col-md12">
					<table id="processTable" class="layui-table" lay-filter="processTable"></table>
				</div>
			</div>
		</div>
	</div>
	<script type="text/html" id="detailTableToolbar">
		<div class="layui-inline" shiro:hasPermission="btn:settle_complet">
			<button class="layui-btn layui-btn-sm" lay-event="settle"><i class="layui-icon">&#xe605;</i>发起结算</button>
		</div>
		<div class="layui-inline" shiro:hasPermission="btn:settle_record">
			<button class="layui-btn layui-btn-sm" lay-event="record"><i class="layui-icon">&#xe68d;</i>结算记录</button>
		</div>
	</script>
	<script type="text/html" id="processTableToolbar">
		<div class="layui-inline" shiro:hasPermission="btn:order_complet">
			<button class="layui-btn layui-btn-sm" lay-event="complet"><i class="layui-icon">&#xe605;</i>确认</button>
		</div>
		<div class="layui-inline" shiro:hasPermission="btn:order_nullify">
			<button class="layui-btn layui-btn-sm layui-bg-red" lay-event="nullify"><i class="layui-icon">&#xe693;</i>价格作废</button>
		</div>
	</script>
	<script type="text/html" id="barRight">
		<a class="layui-btn layui-btn-sm" lay-event="upd">编辑</a>
	</script>
	<script type="text/javascript" th:inline="javascript">
		layui.use(['layer','table','element','form'],function(){
			var layer = layui.layer,
				table = layui.table,
				form = layui.form,
				element = layui.element;
			var tableIns;
			var tableData;
			var selectId;
			var proqty;
			let selectData;
			let allData;
			$('#form').form('load','manage/sale_order/info?masterId='+[[${id}]]);
			$('#form').form({
				onLoadSuccess: function(data){
					allData = data;
					tableData = data.detailsList;
					table.render({
						elem:'#table'
						,page: true //开启分页
						,limit: 10
						,limits: [10,15,20,30,40,50,100]
						,loading: true
						,cols: [
							[ //表头
								{type:'radio'}
								,{field: 'cinvcode', title: '产品编码', minWidth:'150'}
								,{field: 'cinvname', title: '产品名称', minWidth:'150'}
								,{field: 'type', title: '类型', minWidth:'150'}
								,{field: 'cbatch', title: '批号', minWidth:'150'}
								,{field: 'completFlag', title: '是否定价', minWidth:'120', templet: function (d){
									return d.completFlag?'已定价':'未定价';
								}}
								,{field: 'qty', title: '订单数量', minWidth:'90'}
								,{field: 'sumQty', title: '累计结算数量', minWidth:'120'}
								,{field: 'amount', title: '金额', minWidth:'90'}
								,{field: 'sumAmount', title: '累计结算金额', minWidth:'120'}
								,{field: 'sfsw', title: '是否实物', minWidth:'90'}
								,{field: 'sfll', title: '是否来料', minWidth:'90'}
								,{field: 'llrq', title: '来料日期', minWidth:'90'}
								,{field: 'czjslx', title: '产值计算类型', minWidth:'120'}
								// ,{field: 'sblx', title: '设备类型', minWidth:'90'}
								,{field: 'tsbz', title: '特殊备注', minWidth:'90'}
							]
						]
						,text: {
							none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
						}
						,data: tableData
						,toolbar:'#detailTableToolbar'
						,defaultToolbar: ['']
						,done: function(res,curr,count){
							for(var i in res.data){
								if(!res.data[i].completFlag){
									$("tr[data-index='"+i+"']").attr({"style":"color:red","font-weight":"bold"})
								}
							}
						}
					});
				}
			});

			table.on('toolbar(table)', function(obj) {
				switch (obj.event) {
					case 'settle':
						if (!selectData){
							layer.msg("请先选择一条要结算的数据",{icon: '2'});
							return;
						}
						if(!selectData.completFlag){
							layer.msg("未定价，请先确认价格",{icon: '2'});
							return;
						}
						localStorage.setItem("settleData",JSON.stringify({
							saleOrderMasterId: allData.id,
							saleOrderDetailId: selectData.id,
							cinvcode: selectData.cinvcode,
							saleOrderCode: allData.orderNo,
							detailList: table.cache['processTable'],
							czjslx: selectData.czjslx
						}));
						top.layer.open({
							type: 2
							,title: '结算详情'
							,area: ['60%', '100%']
							,content: '/manage/sale_order/settleHtml/' + selectData.id
							,btn: ['确认结算', '取消']
							,offset: 'r'
							,yes: function (index, layero) {
								let iframeWindow = $(layero).find("iframe")[0].contentWindow;
								iframeWindow.fromData();
								return false;
							},
							end: function () {
								localStorage.removeItem("settleData");
							}
						});
						break;
					case'nullify':
						if (!selectData){
							layer.msg("请先选择一条要结算的数据",{icon: '2'});
							return;
						}
						layer.confirm('确定作废?', {icon: 3, title: '提示'}, function (index) {
							let itm = top.layer.load(0, { shade: 0.3 });
							$.post('manage/sale_order/settle_nullify',{detailsId: selectData.id},function (d){
								top.layer.close(itm);
								if(d.code == "200"){
									layer.msg("结算作废成功",{icon: '1'},function () {
										location.reload();
									});
								}else{
									layer.alert("结算作废失败，"+d.msg,{icon: '2'});
								}
							})
						});
						break;
					case 'record':
						if (!selectData){
							layer.msg("请先选择一条结算的数据",{icon: '2'});
							return;
						}
						top.layer.open({
							type: 2
							,title: "结算记录"
							,maxmin: true
							,area: ['90%', '90%']
							,content: '/manage/settle_order_master_new/index/'+ selectData.id
						});
						break;
				}
			})

			table.on('row(table)', function(obj){
				obj.tr.addClass('layui-table-click').siblings().removeClass('layui-table-click');//选中行样式
				obj.tr.find('input[lay-type="layTableRadio"]').prop("checked",true);

				table.setRowChecked('table', {
					index: 'all', // 所有行
					checked: false // 此处若设置 true，则表示全选
				});

				table.setRowChecked('table', {
					index:obj.index
					,checked: true
				});

				form.render('radio');
				selectId = obj.data.id;
				proqty=obj.data.qty
				selectData = obj.data;
				table.reload('processTable',{
					url:'manage/sale_order/process_info_new',
					where:{detailsId:obj.data.id},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				})
			});

			table.on('radio(table)', function(obj){
				table.setRowChecked('table', {
					index: 'all', // 所有行
					checked: false // 此处若设置 true，则表示全选
				});

				table.setRowChecked('table', {
					index:obj.index
					,checked: true
				});

				selectId = obj.data.id;
				proqty=obj.data.qty
				selectData = obj.data;
				table.reload('processTable',{
					url:'manage/sale_order/process_info_new',
					where:{detailsId:obj.data.id},
					page: {
						curr: 1 //重新从第 1 页开始
					}
				})

			});

			// 订单工序信息
			tableIns = table.render({
				elem:'#processTable'
				,page: true //开启分页
				,limit: 10
				,limits: [10,15,20,30,40,50,100]
				,loading: true
				,cols: [
					[ //表头
						{field: 'serialNumber', title: '序列号', minWidth:'150'}
						,{field: 'orderProcess', title: '订单工序', minWidth:'150'}
						,{field: 'orderProcessName', title: '工序名称', minWidth:'150'}
						,{field: 'sblx', title: '设备类型', minWidth:'90'}
						// ,{field: 'pricingMethod', title: '计价方式', minWidth:'150'}
						,{field: 'expectHours', title: '标准工时', minWidth:'150',edit:true}
						,{field: 'ioritaxcost', title: '价格', minWidth:'90',edit:true}
						,{field: 'amount', title: '金额', minWidth:'90'}
						// ,{fixed: 'right', title: '操作',toolbar: '#barRight'}
					]
				]
				,text: {
					none: '暂无相关数据' //默认：无数据。注：该属性为 layui 2.2.5 开始新增
				}
				,data: []
				,toolbar:'#processTableToolbar'
				,defaultToolbar: ['']
			});

			table.on('toolbar(processTable)', function(obj) {
				switch (obj.event) {
					case 'complet':
						if (!selectData){
							layer.msg("请先选择一条销售订单表体数据",{icon: '2'});
							return;
						}
						let datas = table.cache['processTable'];
						for(var i in datas){
							if(datas[i].ioritaxcost == null || datas[i].ioritaxcost === '' ){
								layer.msg("订单工序信息中第"+(++i)+"行数据的价格为空",{icon: '2'});
								return;
							}
							if(selectData.czjslx.includes('时间')) {
								if(datas[i].expectHours == null || datas[i].expectHours === '' ){
									layer.msg("订单工序信息中第"+(++i)+"行数据的标准工时为空",{icon: '2'});
									return;
								}
							}
						}

						selectData.mark = false;
						selectData.process = datas;

						if(selectData.czjslx !== '按批次') {
							// 询问是否更新价格工序表
							top.layer.confirm('是否更新价格工序表?', {icon: 3, title: '提示'}, function (index) {
								selectData.mark = true;
								top.layer.close(index);
								saveData(selectData)
							}, function (index) {
								top.layer.close(index);
								saveData(selectData)
							});
						}else {
							saveData(selectData)
						}
						break;
					case'nullify':
						if (!selectData){
							layer.msg("请先选择一条销售订单表体数据",{icon: '2'});
							return;
						}
						layer.confirm('确定作废?', {icon: 3, title: '提示'}, function (index) {
							let itm = top.layer.load(0, { shade: 0.3 });
							$.post('manage/sale_order/price_nullify',{detailsId: selectData.id},function (d){
								top.layer.close(itm);
								if(d.code == "200"){
									layer.msg("价格作废成功",{icon: '1'},function () {
										location.reload();
									});
								}else{
									layer.alert("价格作废失败，"+d.msg,{icon: '2'});
								}
							})
						});
						break;
				}
			})

			function saveData(d){
				//如果是按批次
				if(d.czjslx === '按批次') {
					layer.prompt({title: '价格'}, function(value, index, elem){

						// 值的校验
						if(value.replace(/\s/g, '') === ''){
							layer.tips('值不能为空', elem, {tips: 1});
							return elem.focus();
						}

						//判断是否为数字
						if(value.replace(/^(0|([1-9][0-9]*))(\.[\d]+)?$/) === value){
							layer.tips('只能是数字', elem, {tips: 1});
							return elem.focus();
						}
						d.amount = value;

						savePost(d)
						layer.close(index);
					});
				}else {
					savePost(d)
				}
			}

			function savePost(da){
				let itm = top.layer.load(0, { shade: 0.3 });
				$.post('manage/sale_order/price_set',{detail: JSON.stringify(da)},function (d){
					top.layer.close(itm);
					if(d.code == "200"){
						layer.msg("确认成功",{icon: '1'},function () {
							location.reload();
						});
					}else{
						layer.alert("确认失败，"+d.msg,{icon: '2'});
					}
				})
			}

			// 单元格编辑事件
			table.on('edit(processTable)', function(obj){

				var field = obj.field; // 得到修改的字段
				var value = obj.value // 得到修改后的值
				var oldValue = obj.oldValue // 得到修改前的值 -- v2.8.0 新增

				if(selectData.czjslx.includes('时间')) {
					// 值的校验
					if(value.replace(/\s/g, '') === ''){
						layer.tips('值不能为空', this, {tips: 1});
						value = Number(oldValue);
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}

					//判断是否为数字
					if(value.replace(/^(0|([1-9][0-9]*))(\.[\d]+)?$/) === value){
						value = Number(oldValue);
						layer.tips('只能是数字', this, {tips: 1});
						return obj.reedit(); // 重新编辑 -- v2.8.0 新增
					}
				}else {
					if (field === 'ioritaxcost'){
						// 值的校验
						if(value.replace(/\s/g, '') === ''){
							layer.tips('值不能为空', this, {tips: 1});
							value = Number(oldValue);
							return obj.reedit(); // 重新编辑 -- v2.8.0 新增
						}

						//判断是否为数字
						if(value.replace(/^(0|([1-9][0-9]*))(\.[\d]+)?$/) === value){
							value = Number(oldValue);
							layer.tips('只能是数字', this, {tips: 1});
							return obj.reedit(); // 重新编辑 -- v2.8.0 新增
						}
					}
				}

				// 更新当前缓存数据
				var update = {};
				update[field] = value;
				obj.update(update, true); // 参数 true 为 v2.7 新增功能，即同步更新其他包含自定义模板并可能存在关联的列视图
			});

			table.on('tool(processTable)', function(obj) {
				switch (obj.event) {
					case 'upd':
						top.layer.open({
							type: 2
							,title: '修改'
							,area: ['50%', '100%']
							,content: '/manage/common/editHtml/sale_order_process/' + obj.data.id
							,btn: ['保存', '取消']
							,offset: 'r'
							,yes: function (index, layero) {
								var iframeWindow = $(layero).find("iframe")[0].contentWindow;
								var data = iframeWindow.getFormDataAndValidate();
								// 金额计算规则
								if (data.pricingMethod=="计件"){
									data.jjfsje=proqty*data.ioritaxcost
								}else if (data.pricingMethod=="计时"){
									data.jjfsje=proqty*data.ioritaxcost*data.expectHours
								}else if (data.pricingMethod=="按批") {
									data.jjfsje = proqty
								}
								if (data.sign){
									if (!data.pricingMethod){
										top.layer.msg("请选择【计价方式】")
										return;
									}else {
										if (data.pricingMethod === '计时'){
											if(!Number.parseInt(data.expectHours)){
												top.layer.msg("【计价方式】为【计时】的时候，【标准工时】不能为0")
												return;
											}
										}
									}
									let shadeIndex = top.layer.msg('数据提交中，请稍候', {icon: 16, time: false, shade: 0.4});
									$.post("/manage/common/update", {url: 'sale_order_process', obj: JSON.stringify(data)}, function (d) {
										top.layer.close(shadeIndex);
										if (d.code === 200) {
											top.layer.msg("修改成功", {icon: 1,time:1000},function () {
												$.post('manage/sale_order/process_info',{detailsId: selectId},function (d){
													//添加单价表
													$.post('manage/sale_order/process_info_price',{detailsId: selectId,processId:data.id})
													tableIns = table.reload('processTable',{
														data: d
														,done: function (d) {
															top.layer.close(index)
														}
													})
												})
											});
										} else {
											top.layer.msg("修改失败," + d.msg, {icon: 2});
										}
										layer.close(index);
									}, "json")
								}
								return false;
							}
						});
						break;
				}
			})
		})
	</script>
</body>
</html>